import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'
import conf from '@/config'

const service = axios.create({
  baseURL: conf.baseURL, // url = base url + request url
  timeout: 30000 // request timeout
})

let requestCount = 0
function openLoading() {
  store.commit('app/SET_IS_LOADING', true)
  requestCount++
}
function closeLoading() {
  requestCount--
  if (requestCount <= 0) {
    store.commit('app/SET_IS_LOADING', false)
  }
}

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    openLoading()
    if (store.state.user.token) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    closeLoading()
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    closeLoading()
    if (res.code && res.code !== 200) {
      if (res.code === 401) {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      } else {
        ElMessage({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    closeLoading()
    if (error.response && error.response.data.message) {
      ElMessage({
        message: error.response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
    }

    if (error.response.data.code === 401) {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    }
    return Promise.reject(error.response.data)
  }
)

const request = (config: AxiosRequestConfig, timeout3 = 30000) => {
  config.timeout = timeout3
  return service(config)
}

export function getAjax(url: string, params?: any) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'get',
      params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function postAjax(url: string, data?: any) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'post',
      data
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function postAjaxWithParams(url: string, params?: any) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'post',
      params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function putAjax(url: string, data?: any) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'put',
      data
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function deleteAjax(url: string, data?: any) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'delete',
      data
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function download(url: string) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: conf.baseURL + url,
      responseType: 'blob',
      headers: { Authorization: 'Bearer ' + getToken() }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export default request
